package com.sz.zhiling.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtils {

    private Logger logger = Logger.getLogger(JwtUtils.class);

    private static String id = "zhiling";
    private static long ttl = 3600000;//一个小时

    //创建一个标签
    public String createjwt(String sub,String roles){
        long t = System.currentTimeMillis();//当前时间
        Date date = new Date(t);//签发时间
        Date exp = new Date(t+ttl);//过期时间

        JwtBuilder jb = Jwts.builder().setId(id).setIssuedAt(date).setExpiration(exp).setSubject(sub)
                .signWith(SignatureAlgorithm.HS256,id).claim("roles",roles);
        String str = jb.compact();
        return str;
    }

    //解析token
    public Claims parseToken(String token){
        Claims claims = Jwts.parser().setSigningKey(id).parseClaimsJws(token).getBody();
        logger.debug("id = "+claims.getId());
        logger.debug("getSubject = " + claims.getSubject());
        logger.debug("getIssuedAt = " + claims.getIssuedAt());
        logger.debug("getExpiration = " + claims.getExpiration());
        logger.debug("roles = " + claims.get("roles"));
        return claims;
    }
}
